from flask import Blueprint, request, jsonify, current_app
from app.celery_task.tasks import add

test_bp = Blueprint('test', __name__)

@test_bp.route('/test_celery', methods=['GET'])
def test_celery():
    try:
        # 异步调用任务
        task = add.delay(4, 6)
        
        # 返回任务ID，前端可以用这个ID查询任务状态
        return jsonify({
            'success': True,
            'task_id': task.id,
            'message': '任务已提交'
        })
        
    except Exception as e:
        current_app.logger.error(f"Celery任务提交失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '任务提交失败'
        }), 500

@test_bp.route('/get_task_result/<task_id>', methods=['GET'])
def get_task_result(task_id):
    try:
        # 获取任务实例
        task_result = add.AsyncResult(task_id)
        
        response = {
            'task_id': task_id,
            'status': task_result.status,
        }
        
        # 如果任务完成，返回结果
        if task_result.ready():
            response['result'] = task_result.get()
            
        return jsonify(response)
        
    except Exception as e:
        current_app.logger.error(f"获取任务结果失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '获取任务结果失败'
        }), 500


